import axios from "axios"
import * as Utils from "@/utils"

class HttpService {
  constructor() {
    this.timeout = 5 * 60 * 1000
    this.env = Utils.getEnv()
    this.baseApiUrl = this.env === "prod" ? "https://thunders.com.hk/website" : window.location.origin
  }

  showLoading() {
    console.log("showLoading")
  }

  closeLoading() {
    console.log("closeLoading")
  }

  getHeaders(contentType) {
    return {
      Authorization: "",
      "Content-type": contentType || "application/json;charset=utf-8",
      Token: localStorage.getItem("token") || "",
      Rejectunauthorized: false,
    }
  }

  responseError(data) {
    //const message = data.message || data.msg || "小主，我有点累，请稍后再试"
    console.log(data)
  }
  // get
  get(path, data, config = { showLoading: false }) {
    if (config.showLoading) this.showLoading()
    return new Promise((resolve, reject) => {
      axios({
        method: "get",
        headers: { ...this.getHeaders("application/x-www-form-urlencoded") },
        url: `${this.baseApiUrl}${this.getContext()}${path}?${Utils.qsString(data)}`,
      })
        .then((response) => {
          if (response.data?.code == "200") {
            resolve(response.data || {})
          } else {
            this.responseError(response.data)
            reject({})
          }
        })
        .catch((error) => {
          reject(error || {})
        })
        .finally(() => {
          if (config.showLoading) this.closeLoading()
        })
    })
  }
  // post
  post(path, data, config = { showLoading: false }) {
    if (config.showLoading) this.showLoading()
    return new Promise((resolve, reject) => {
      axios({
        timeout: this.timeout,
        method: "post",
        headers: { ...this.getHeaders() },
        url: `${this.baseApiUrl}${this.getContext()}${path}`,
        data: data,
      })
        .then((response) => {
          if (response.data?.code == "200") {
            resolve(response.data || {})
          } else {
            this.responseError(response.data)
            reject({})
          }
        })
        .catch((error) => {
          reject(error || {})
        })
        .finally(() => {
          if (config.showLoading) this.closeLoading()
        })
    })
  }
  //获取接口上下文
  getContext() {
    if (this.env !== "dev") {
      return ""
    }
    return "/api"
  }
}

export default new HttpService()
